package cz.data.domain.metadata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cz.data.common.mybatis.BaseServiceImpl;
import cz.data.common.core.RedisConstant;
import cz.data.common.redis.service.RedisService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cz.data.domain.metadata.dao.MetadataAuthorizeDao;
import cz.data.domain.metadata.model.dto.MetadataAuthorizeDto;
import cz.data.domain.metadata.model.entity.MetadataAuthorizeEntity;
import cz.data.domain.metadata.service.MetadataAuthorizeService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MetadataAuthorizeServiceImpl extends BaseServiceImpl<MetadataAuthorizeDao, MetadataAuthorizeEntity> implements MetadataAuthorizeService {

    @Autowired
    private MetadataAuthorizeDao metadataAuthorizeDao;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<String> getAuthorizedMetadata(String id) {
        List<MetadataAuthorizeEntity> metadataAuthorizeList = metadataAuthorizeDao.selectList(Wrappers.<MetadataAuthorizeEntity>lambdaQuery().eq(MetadataAuthorizeEntity::getRoleId, id));
        return metadataAuthorizeList.stream()
                .map(MetadataAuthorizeEntity::getObjectId)
                .collect(Collectors.toList());
    }

    @Override
    public void metadataAuthorize(MetadataAuthorizeDto metadataAuthorizeDto) {
        // 先删除
        metadataAuthorizeDao.delete(Wrappers.<MetadataAuthorizeEntity>lambdaQuery().eq(MetadataAuthorizeEntity::getRoleId, metadataAuthorizeDto.getRoleId()));
        metadataAuthorizeDto.getAuthorizeDataList().forEach(s -> {
            MetadataAuthorizeEntity metadataAuthorizeEntity = new MetadataAuthorizeEntity();
            metadataAuthorizeEntity.setRoleId(s.getRoleId());
            metadataAuthorizeEntity.setObjectId(s.getObjectId());
            metadataAuthorizeEntity.setObjectType(s.getObjectType());
            metadataAuthorizeDao.insert(metadataAuthorizeEntity);
        });
    }

    @Override
    public void refreshCache() {
        String authorizeKey = RedisConstant.METADATA_AUTHORIZE_KEY;
        Boolean hasAuthorizeKey = redisService.hasKey(authorizeKey);
        if (hasAuthorizeKey) {
            redisService.del(authorizeKey);
        }
        List<MetadataAuthorizeEntity> metadataAuthorizeList = metadataAuthorizeDao.selectList(Wrappers.emptyWrapper());
        Map<String, List<MetadataAuthorizeEntity>> authorizeListMap = metadataAuthorizeList.stream().collect(Collectors.groupingBy(MetadataAuthorizeEntity::getRoleId));
        redisTemplate.opsForHash().putAll(authorizeKey, authorizeListMap);
    }

    @Override
    public List<MetadataAuthorizeEntity> getMetadataAuthorizeByRoleId(String role) {
        QueryWrapper<MetadataAuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MetadataAuthorizeEntity::getRoleId, role);
        return list(queryWrapper);
    }

    @Override
    public Set<String> authorities(Collection<String> roleIds, Predicate<String> typeFilter) {
        QueryWrapper<MetadataAuthorizeEntity> queryWrapper = new QueryWrapper<>();
        if (CollectionUtils.isNotEmpty(roleIds)) {
            queryWrapper.lambda().in(MetadataAuthorizeEntity::getRoleId, roleIds);
        }
        return list(queryWrapper)
                .stream()
                .filter(authorities -> typeFilter.test(authorities.getObjectType()))
                .map(MetadataAuthorizeEntity::getObjectId)
                .collect(Collectors.toSet());
    }
}
